package cn.gcyl.module.biz.service.memberorder;

import cn.gcyl.module.biz.dal.dataobject.SysMemberUserDO;
import cn.gcyl.module.biz.dal.dataobject.SysPayOrderDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceRegistrationInformationDO;
import cn.gcyl.module.biz.dal.dataobject.membershipsettings.MembershipSettingsDO;
import cn.gcyl.module.biz.dal.mysql.SysMemberUserMapper;
import cn.gcyl.module.biz.dal.mysql.SysPayOrderMapper;
import cn.gcyl.module.biz.dal.mysql.membershipsettings.MembershipSettingsMapper;
import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import cn.gcyl.module.biz.controller.admin.memberorder.vo.*;
import cn.gcyl.module.biz.dal.dataobject.memberorder.MemberOrderDO;
import cn.gcyl.framework.common.pojo.PageResult;
import cn.gcyl.framework.common.pojo.PageParam;
import cn.gcyl.framework.common.util.object.BeanUtils;

import cn.gcyl.module.biz.dal.mysql.memberorder.MemberOrderMapper;

import static cn.gcyl.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.gcyl.framework.common.util.collection.CollectionUtils.convertList;
import static cn.gcyl.framework.common.util.collection.CollectionUtils.diffList;
import static cn.gcyl.module.system.enums.ErrorCodeConstants.MEMBER_ORDER_NOT_EXISTS;

/**
 * 会员订单管理 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class MemberOrderServiceImpl implements MemberOrderService {

    @Resource
    private MemberOrderMapper memberOrderMapper;
    @Resource
    private SysPayOrderMapper sysPayOrderMapper;// 新增方法：支付成功后更新用户会员状态
    @Resource
    private SysMemberUserMapper sysMemberUserMapper;
    @Resource
    private MembershipSettingsMapper membershipSettingsMapper;

    @Override
    public Long createMemberOrder(MemberOrderSaveReqVO createReqVO) {
        // 插入
        MemberOrderDO memberOrder = BeanUtils.toBean(createReqVO, MemberOrderDO.class);
        memberOrderMapper.insert(memberOrder);

        // 返回
        return memberOrder.getId();
    }

    @Override
    public void updateMemberOrder(MemberOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateMemberOrderExists(updateReqVO.getId());
        // 更新
        MemberOrderDO updateObj = BeanUtils.toBean(updateReqVO, MemberOrderDO.class);
        memberOrderMapper.updateById(updateObj);
    }

    @Override
    public void deleteMemberOrder(Long id) {
        // 校验存在
        validateMemberOrderExists(id);
        // 删除
        memberOrderMapper.deleteById(id);
    }

    @Override
        public void deleteMemberOrderListByIds(List<Long> ids) {
        // 删除
        memberOrderMapper.deleteByIds(ids);
        }


    private void validateMemberOrderExists(Long id) {
        if (memberOrderMapper.selectById(id) == null) {
            throw exception(MEMBER_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public MemberOrderDO getMemberOrder(Long id) {
        return memberOrderMapper.selectById(id);
    }

    @Override
    public PageResult<MemberOrderDO> getMemberOrderPage(MemberOrderPageReqVO pageReqVO) {
        return memberOrderMapper.selectPage(pageReqVO);
    }
    @Override
    public Boolean getMemberOrderByOrderNo(String merchantOrderId, SysPayOrderDO sysPayOrderDO) {
        SysPayOrderDO payOrderDO = sysPayOrderMapper.selectById(sysPayOrderDO.getId());
        if (payOrderDO.getStatus() == 10) {
            MemberOrderDO memberOrderDO = memberOrderMapper.selectOne(MemberOrderDO::getOrderNo, merchantOrderId);
            memberOrderDO.setPayStatus(1);
            memberOrderMapper.updateById(memberOrderDO);

            // 支付成功后更新用户会员状态
            updateUserMemberStatus(memberOrderDO);
        }
        return true;
    }
    private void updateUserMemberStatus(MemberOrderDO memberOrderDO) {
        // 获取用户信息
        SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(memberOrderDO.getUserId());
        if (sysMemberUserDO == null) {
            return;
        }

        // 根据订单中的会员名称查找会员设置
        MembershipSettingsDO membershipSettingsDO = membershipSettingsMapper.selectOne(
                MembershipSettingsDO::getMembershipName, memberOrderDO.getMembershipName());
        if (membershipSettingsDO == null) {
            return;
        }

        LocalDateTime now = LocalDateTime.now();
        Integer number = memberOrderDO.getNumber() != null ? memberOrderDO.getNumber().intValue() : 0;

        // 更新会员状态
        sysMemberUserDO.setMemberId(membershipSettingsDO.getId());
        sysMemberUserDO.setAccumulatedQuantity(number);
        sysMemberUserDO.setMemberPurchaseDate(now);

        // 计算会员到期时间：如果是续费，则在原到期时间基础上增加；否则从现在开始计算
        LocalDateTime newExpirationDate;
        if (sysMemberUserDO.getMemberExpirationDate() != null &&
                sysMemberUserDO.getMemberExpirationDate().isAfter(now)) {
            // 续费情况：在原有到期时间基础上增加
            newExpirationDate = sysMemberUserDO.getMemberExpirationDate().plusDays(
                    membershipSettingsDO.getLifeSpan() * number);
        } else {
            // 新购或过期后重新购买：从现在开始计算
            newExpirationDate = now.plusDays(membershipSettingsDO.getLifeSpan() * number);
        }
        sysMemberUserDO.setMemberExpirationDate(newExpirationDate);

        // 增加咨询和报名次数（考虑已有的次数）
        Long additionalConsultation = membershipSettingsDO.getConsultationFrequency() * number;
        Long additionalRegistration = membershipSettingsDO.getRegistrationsFrequency() * number;

        sysMemberUserDO.setConsultationsTotalNumber(
                (sysMemberUserDO.getConsultationsTotalNumber() == null ? 0 : sysMemberUserDO.getConsultationsTotalNumber())
                        + additionalConsultation);
        sysMemberUserDO.setRegistrationsTotalNumber(
                (sysMemberUserDO.getRegistrationsTotalNumber() == null ? 0 : sysMemberUserDO.getRegistrationsTotalNumber())
                        + additionalRegistration);
        sysMemberUserDO.setRemainingConsultationFrequency(
                (sysMemberUserDO.getRemainingConsultationFrequency() == null ? 0 : sysMemberUserDO.getRemainingConsultationFrequency())
                        + additionalConsultation);
        sysMemberUserDO.setRemainingRegistrationsFrequency(
                (sysMemberUserDO.getRemainingRegistrationsFrequency() == null ? 0 : sysMemberUserDO.getRemainingRegistrationsFrequency())
                        + additionalRegistration);

        sysMemberUserMapper.updateById(sysMemberUserDO);
    }

}